package com.hmdp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;

import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hmdp.utils.RedisWorker;
import com.hmdp.utils.UserHolder;
import io.lettuce.core.RedisBusyException;
import io.lettuce.core.RedisCommandExecutionException;
import lombok.extern.slf4j.Slf4j;
;
import org.redisson.api.RedissonClient;


import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.ClassPathResource;

import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@DependsOn("redissonClient")
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisWorker redisWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    private  final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
    private volatile boolean running = true; // 新增运行状态标志
    @PostConstruct
    public void init(){
        EXECUTOR_SERVICE.submit(new VoucherOrderHandler());
    }
    @PreDestroy
    public void destroy() {
        log.info("开始关闭订单服务...");
        running = false; // 先设置标志位
        EXECUTOR_SERVICE.shutdown(); // 启动优雅关闭

        try {
            // 等待线程处理完当前消息
            if (!EXECUTOR_SERVICE.awaitTermination(2, TimeUnit.SECONDS)) {
                log.warn("线程池未及时关闭，尝试强制终止");
                EXECUTOR_SERVICE.shutdownNow();
            }
        } catch (InterruptedException e) {
            log.warn("关闭过程中被中断", e);
            EXECUTOR_SERVICE.shutdownNow();
            Thread.currentThread().interrupt();
        }
        log.info("订单服务已关闭");
    }
    private class VoucherOrderHandler implements Runnable{
        String queueName="stream.orders";
        String groupName = "g1";
        String consumerName = "c1";
        private void initConsumerGroup() {
            try {
                stringRedisTemplate.opsForStream().createGroup(queueName, ReadOffset.latest(), groupName);
                log.info("成功创建消费者组: {} for stream: {}", groupName, queueName);
            } catch (RedisSystemException e) {
                if (e.getRootCause() instanceof RedisBusyException) {
                    log.info("消费者组已存在: {}", groupName);
                } else if (e.getRootCause() instanceof RedisCommandExecutionException
                        && e.getRootCause().getMessage().contains("no such key")) {
                    // Stream不存在，等待后续自动创建
                    log.info("Stream {} 不存在，等待创建...", queueName);
                } else {
                    log.error("初始化消费者组失败", e);
                }
            }
        }
        @Override
        public void run() {
            initConsumerGroup();
            while (running && !Thread.currentThread().isInterrupted()) {
                try {
                    // 从消息队列获取信息
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty()
                                    .count(1)
                                    .block(Duration.ofMillis(500)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    if (mapRecords == null || mapRecords.isEmpty()) {
                        continue;
                    }

                    // 处理订单
                    MapRecord<String, Object, Object> mapRecord = mapRecords.get(0);
                    Map<Object, Object> values = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    createOrder(voucherOrder);

                    // ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", mapRecord.getId());

                } catch (RedisSystemException e) {
                    // 处理Redis系统异常（包括底层的中断）
                    if (e.getRootCause() instanceof InterruptedException) {
                        log.info("收到中断信号，准备退出消费者循环");
                        Thread.currentThread().interrupt();
                        break;
                    }
                    log.error("Redis系统异常", e);
                    handleListError();
                } catch (Exception e) {
                    log.error("订单处理异常", e);
                    handleListError();
                }
            }
            log.info("订单处理器已停止");
        }
        private void handleListError() {
            while(running &&!Thread.currentThread().isInterrupted()){
                //从消息队列中获取信息

                try {
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //如果消息队列中没有数据,此时代表异常数据为空，直接跳出循环
                    if(mapRecords==null || mapRecords.isEmpty()){
                       break;
                    }
                    MapRecord<String, Object, Object> mapRecord = mapRecords.get(0);
                    Map<Object, Object> values = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //有数据创建订单
                    createOrder(voucherOrder);
                    //ACK确认消息
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",mapRecord.getId());
                } catch (Exception e) {
                    log.error("订单pending-list处理异常",e);

                }
            }
        }
    }
    private static final DefaultRedisScript<Long> SECILL_SCRIPT;
    static {
        SECILL_SCRIPT = new DefaultRedisScript<>();
        SECILL_SCRIPT.setResultType(Long.class);
        SECILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
    }
    @Override
    public Result seckill(Long voucherId) {
        //调用lua脚本
        Long userId=UserHolder.getUser().getId();
        Long orderId = redisWorker.generateId("order");
        Long result = stringRedisTemplate.execute(
                SECILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), orderId.toString()
        );
        //判断返回结果是否为0
       int r=result.intValue();
        if(r!=0){
            return Result.fail(r==1?"库存不足!":"同一个用户不能重复下单!");
        }
        //为0则代表有资格进行秒杀活动

        //执行完lua脚本之后，记得更新数据库中的库存
        seckillVoucherService.update().setSql("stock=stock-1").eq("voucher_id",voucherId).update();
        //最后返回订单id
        return Result.ok(orderId);
    }

    public void createOrder(VoucherOrder voucherOrder) {
        log.info("库存扣减成功，开始保存订单");
        save(voucherOrder);
    }
}
